package com.xjscrm.server.biz.mq.consumer;

import com.uzai.mobile.collect.api.enums.MicaMsgType;
import com.xjscrm.server.biz.mq.hander.ConsumerHandler;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author mingyang.chen create in 2023/4/25 17:22
 */
@Component
public class MsgTriggerTaskProcessorHolder implements ApplicationContextAware {

    private static final Map<MicaMsgType, ConsumerHandler> processorCache = new ConcurrentHashMap<>();
    private static final List<ConsumerHandler> postProcessorCache = new ArrayList<>();

    // 匹配处理器
    public static ConsumerHandler matchProcessor(MicaMsgType micaMsgType) {
        return processorCache.get(micaMsgType);
    }

    public static List<ConsumerHandler> allPostProcessor() {
        return postProcessorCache;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, ConsumerHandler> msgTriggerTaskProcessorCache = applicationContext.getBeansOfType(ConsumerHandler.class);

        for (ConsumerHandler value : msgTriggerTaskProcessorCache.values()) {
            if (Objects.isNull(value.msgType())) {
                throw new IllegalArgumentException("msgType for MsgTriggerTaskProcessor required");
            }
            processorCache.put(value.msgType(), value);
        }
    }
}

